package com.xd.controller;


import com.alibaba.fastjson.JSONObject;
import com.xd.bean.ManInfo;
import com.xd.bean.PersonInfo;
import com.xd.bean.Record;
import com.xd.service.IPersonInfoService;
import com.xd.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author gxd
 * @Date： 2018/3/12
 * jar运行 注意new modelAndView 开头没有/
 *
 */

@Controller
@RequestMapping(value = "user")
public class InfoController {
    @Autowired
    IPersonInfoService personInfoService;

    @Value("${ky.key}")
    private String key;
    @Value("${ky.secret}")
    private String secret;
    @Value("${ky.url}")
    private String url;

//    Logger logger=LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "/index")
    public ModelAndView index(HttpServletRequest request, HashMap<String, Object> map){
        String callbackurl=request.getParameter("callback");
        map.put("url", callbackurl);
        String ip= IPUtil.getIpAddr(request);
        map.put("ip", ip);
        return new ModelAndView("userInfo");
    }





    @RequestMapping(value = "/add")
    public @ResponseBody Map<String, Object> addActivity(HttpServletRequest request, PersonInfo personInfo) {
        ModelMap map=new ModelMap();
        Integer r= null;
        try {
            r = personInfoService.addInfo(personInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("result", r);
        return map;
    }





    @RequestMapping(value = "/man")
    public ModelAndView man(HttpServletRequest request,HashMap<String, Object> map){
        String callbackurl=request.getParameter("callback");
        map.put("url", callbackurl);
        String ip=IPUtil.getIpAddr(request);
        map.put("ip", ip);
        return new ModelAndView("man");
    }


    @RequestMapping(value = "/addMan")
    public @ResponseBody  Map<String, Object> addMan(HttpServletRequest request,HttpServletResponse res) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        ModelMap map=new ModelMap();
        //comePage，userName,tel,province,city,area,address,liuyan(方便接听时间),remark(几盒)
        String ip=IPUtil.getIpAddr(request);
        String userName=request.getParameter("userName");
        String tel=request.getParameter("tel");
        String province=request.getParameter("province");
        String city=request.getParameter("city");
        String area=request.getParameter("area");
        String address=request.getParameter("address");
        String liuyan=request.getParameter("liuyan");
        String remark=request.getParameter("remark");

        String comePage=request.getParameter("comePage");

        String fp=request.getParameter("fp");



        ManInfo manInfo=new ManInfo();
        String mid=Tools.getUUID();
        manInfo.setId(mid);
        manInfo.setIp(ip);
        if(Tools.isEmpty(userName) || Tools.isEmpty(tel)){
            map.put("result", "-1");//必填项为空
            return map;
        }

        manInfo.setUserName(userName);
        manInfo.setTel(tel);
        if(Tools.notEmpty(province)){
            manInfo.setProvince(province);
        }
        if(Tools.notEmpty(city)){
            manInfo.setCity(city);
        }
        if(Tools.notEmpty(area)){
            manInfo.setArea(area);
        }
        if(Tools.notEmpty(address)){
            manInfo.setAddress(address);
        }
        if(Tools.notEmpty(liuyan)){
            manInfo.setLiuyan(liuyan);
        }
        if(Tools.notEmpty(remark)){
            manInfo.setRemark(remark);
        }
        if(Tools.notEmpty(comePage)){
            manInfo.setComePage(comePage);
        }

        //解析fp
        Record record =new Record();
        String callback="";
        if(Tools.notEmpty(fp)){

            fp=Tools.decodeDatabase64(fp);
            String [] str=fp.split("\\|");
            fp=str[0];
            callback=Tools.AES_Decrypt("iMdpgSr64\"2Ck:7!",fp);

            String [] str2=callback.split("\\|");
            callback=str2[9];
            try {
                callback=URLDecoder.decode(callback,"utf-8");
            } catch (UnsupportedEncodingException e) {
                callback=str2[9];
            }

            record.setDate(str2[0]);
            record.setIp(str2[1]);
            record.setAdvuid(str2[2]);
            record.setPlanid(str2[3]);
            record.setAdsid(str2[4]);
            record.setUid(str2[5]);
            record.setZoneid(str2[6]);
            record.setSiteid(str2[7]);
            record.setDeduction(str2[8]);
            record.setRefer(callback);

        }
        manInfo.setCallBackUrl(callback);

        Integer r=personInfoService.addMan(manInfo,record);
        if(r>0){
            map.put("result", "1");//已入库
        }else if(r==-1){
            map.put("result", "2");//手机号已存在
        }else{
            map.put("result", "3");//表单提交失败
        }

        return map;
    }


    @RequestMapping(value = "getInfoList")
    public @ResponseBody  Map<String, Object> getInfoList(HttpServletRequest request,HttpServletResponse res) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        ModelMap map=new ModelMap();
        String page=request.getParameter("comePage");
        String startTime=request.getParameter("startTime");
        String endTime=request.getParameter("endTime");
        List<Map<String,Object>> list=createData(page,startTime,endTime);
        map.put("result",list);
        return map;
    }


    //===========导出相关======
    @RequestMapping(value="exportExcel")
    public String download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileName="用户数据信息导出";
        String page=request.getParameter("comePage");
        String startTime=request.getParameter("startTime");
        String endTime=request.getParameter("endTime");

        List<Map<String,Object>> list=createData(page,startTime,endTime);
        String columnNames[]={"序号","姓名","手机","地址","备注","时间","产品"};
        //列名
        String keys[] ={"id","user_name","tel","address","liuyan","pubtime","remark"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list,keys,columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;
    }

    private List<Map<String,Object>> createData(String page,String startTime,String endTime) {
        //获取需要导出的数据
        List<Map<String,Object>> list=personInfoService.getInfoList(page,startTime,endTime);
        return list;

    }



    //===================快眼cpa接口===================

    @RequestMapping(value = "/addCpa")
    public @ResponseBody  Map<String, Object> addCpa(HttpServletRequest request,HttpServletResponse res) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        ModelMap map=new ModelMap();
        String ip=IPUtil.getIpAddr(request);
        String userName=request.getParameter("userName");
        String tel=request.getParameter("tel");
        String province=request.getParameter("province");
        String city=request.getParameter("city");
        String area=request.getParameter("area");
        String address=request.getParameter("address");
        String liuyan=request.getParameter("liuyan");
        String remark=request.getParameter("remark");

        String comePage=request.getParameter("comePage");

        String f=request.getParameter("f");



        ManInfo manInfo=new ManInfo();
        String mid=Tools.getUUID();
        manInfo.setId(mid);

        manInfo.setIp(ip);
        if(Tools.isEmpty(userName) || Tools.isEmpty(tel)){
            map.put("result", "-1");//必填项为空
            return map;
        }

        manInfo.setUserName(userName);
        manInfo.setTel(tel);
        if(Tools.notEmpty(province)){
            manInfo.setProvince(province);
        }
        if(Tools.notEmpty(city)){
            manInfo.setCity(city);
        }
        if(Tools.notEmpty(area)){
            manInfo.setArea(area);
        }
        if(Tools.notEmpty(address)){
            manInfo.setAddress(address);
        }
        if(Tools.notEmpty(liuyan)){
            manInfo.setLiuyan(liuyan);
        }
        if(Tools.notEmpty(remark)){
            manInfo.setRemark(remark);
        }
        if(Tools.notEmpty(comePage)){
            manInfo.setComePage(comePage);
        }



        Integer r=personInfoService.addMan(manInfo,null);
        if(r>0){
            map.put("result", "1");//已入库

            //回调callback
            callBack(f,mid,ip,tel);

        }else if(r==-1){
            map.put("result", "2");//手机号已存在
        }else{
            map.put("result", "3");//表单提交失败
        }

        return map;
    }


    /**
     * 快眼回调callBack
     */
        private void callBack(String f,String mid,String ip,String tel){
            String ordersn=Tools.getUUID();
            String sign=Tools.md5(key+"|"+f+"|"+secret+"|"+ordersn);

            Map<String, String> param =new HashMap<String, String>();
            param.put("key",key);
            param.put("mobile",tel);
            param.put("ip",ip);
            param.put("f",f);
            param.put("ordersn",ordersn);
            param.put("sign",sign);
            String result=HttpClientUtil.doGet(url,param);


           JSONObject obj = JSONObject.parseObject(result);
           if(obj!=null){
               String status=obj.get("status").toString();
               if("0".equals(status)){
                   //失败修改状态值保存返回消息
                   String msg=obj.get("msg").toString();
                   personInfoService.updateStatus(status,msg,mid);
               }
                //否则不修改  默认是1
           }

        }





    public static void main(String[] args) {

        String fp="cUR5YkZvd01ydVN6azNqbTA5clFORVo4cGgxKzNnVWw1WFJZVUJURGxsM3pjL3RydjJuakZDUzY2U1Zya3lYeHJ2M0dxWTRiaWFxZSs3ZkN4S1BCT0tpL1VOVGFXUGNoRVVNekJiRFlCbm5LaG96bzUzU2MraTFwck5Od3lFRW1OaEFzekhhclRTb1hVUmFSaHNMbE4wcHpWYnpyZm02VEl2emlPM0ppZzdVPXw0MjM1MjhjZjMzODI5MjhmOGM5YjQ0NTI2NGNiYmI4Yw==";
        fp=Tools.decodeDatabase64(fp);
        String [] str=fp.split("\\|");
        fp=str[0];
        String sign=str[1];

        System.out.println("fp:"+fp);

        String  callback=Tools.AES_Decrypt("iMdpgSr64\"2Ck:7!",fp);
        System.out.println("callback:"+callback);
        String [] str2=callback.split("\\|");
        callback=str2[9];

        try {
            callback=URLDecoder.decode(callback,"utf-8");
        } catch (UnsupportedEncodingException e) {

        }
        System.out.println("callback:"+callback);


        /*String sign2=Tools.md5("cpa|"+fp+"|aAGEHsUBmId4CaufKbUhszFoLGB22CSh");


        System.out.println("fp:"+fp);
        System.out.println("sign:"+sign);
        System.out.println("sign2:"+sign2);*/
    }


}
